package com.ff.javamonkey.sqlite;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.util.Log;

/**
 * As of now, this file object is still constructed using an Android library (Context).
 * Future revision: Eliminate this dependency entirely.
 * @author rhama_arya
 */
public class SqliteExporter {
	// Debugger
	private static final String TAG = "SqliteExporter";
	// returned status
	public static final int FILE_EXCEPTION = -1;
	public static final int EXPORT_FAILED = -2;
	public static final int FILE_NOT_FOUND = -3;
	public static final int EXPORT_SUCCEED = 1;
	public static final int EXPORT_IN_PROGRESS = 2;
	// File
	private File mSqlite;
	// Context
	private Context mContext;
	
	public SqliteExporter(Context context) {
		this.mContext = context;
	}
	
	/**
	 * Copy database from a File, to a named database. If a previous database exists,
	 * delete it.
	 * @param from imported File to read.
	 * @param to database name.
	 */
	public void copyDatabase(File from, String to) throws IOException {
		File dbFile = mContext.getDatabasePath(to);
		if (dbFile.exists()) {
			// database already existed. Drop it.
			if (mContext.deleteDatabase(to)) {
				Log.d(TAG, "deleteDatabase(): database deleted.");
			}
			else {
				Log.d(TAG, "deleteDatabase(): database NOT deleted.");
				// We had to figure out the way to report this to the user.
				return;
			}
		}
		if (!from.exists()) {
			Log.d(TAG, "no imported data file exists. Aborting");
			return;
		}
		try {
			InputStream is = new BufferedInputStream(new FileInputStream(from));
			if (!dbFile.exists()) {
				String parentPath = dbFile.getParent();
				File parentDir = new File(parentPath);
				parentDir.mkdirs();
				dbFile.createNewFile();
			}
			
			FileOutputStream fos = new FileOutputStream(dbFile);
			byte[] tmp = new byte[1024];
			while (is.read(tmp) > 0) {
				fos.write(tmp);
			}
			is.close();
			fos.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}
